<?php
/**
 * Created by PhpStorm.
 * User: hedonglin
 * Date: 2017/10/27
 * Time: 9:01
 */

namespace app\admin\controller;


use think\Controller;
use think\Db;
use think\Request;
use app\admin\model\Etask as EtaskModel;

class Etask extends Controller
{
    public $table_etask = 'oes_etask';
    public $table_user = 'user';

    /**评教任务页面视图渲染
     * @return mixed
     */
    public function index(){
        return $this->fetch();
    }

    /**
     * 分页查询评教任务
     * @param int $pageNumber
     * @param int $pageSize
     * @param string $searchText
     * @return \think\response\Json
     */
    public function getList($pageNumber = 1, $pageSize = 5, $searchText = ''){
        $result = DB::table(array($this->table_etask=>'task',$this->table_user=>'user'))
            ->field('task.*,user.username,user.nickname')
            ->where("task.createuser_id=user.id")//连表条件
            ->where('task.id = :id or task.name LIKE :name'
                ,['id'=>$searchText ,'name'=>'%'.$searchText.'%'])//查询条件
            ->order("task.id,task.start_data,task.end_data")->paginate($pageSize, false, ["page"=>$pageNumber]);

        return json($result);
    }

    public function addEtask(Request $request){
        $data = $request->only(['name', 'start_data', 'end_data', 'create_data']);
        $result = EtaskModel::create($data);
        if ($result) {
            return json(['success'=>true, "msg"=>'新增成功']);
        } else {
            return json(['success'=>false, "msg"=>'新增失败']);
        }
    }

    /**
     * 开启评教
     * @param $id
     * @return \think\response\Json
     */
    public function startEtask($id){
        $etask = new EtaskModel();
        $etask->startTrans();
        try {
            //将所有的状态设置为未开启，0 未开启  1 开启
            $etask->execute("update oes_etask SET `status` = ?",[0]);
            $etask->execute("update oes_etask SET `status` = ? WHERE id=?",[1,$id]);
        } catch (Exception $e) {
            $etask->rollback();
            return json(['success'=>false, "msg"=>'开启失败']);
        }
        $etask->commit();
        return json(['success'=>true, "msg"=>'开启成功']);
    }

    /**
     * 关闭评教
     * @return \think\response\Json
     */
    public function overEtask(){
        $etask = new EtaskModel();
        //将所有的状态设置为未开启，0 未开启  1 开启
         $etask->execute("update oes_etask SET `status` = ?",[0]);
        return json(['success'=>true, "msg"=>'关闭成功']);
    }



}